<?php
/**
 * @ClassName: Apply
 * @Description: 商户入驻
 * @author: gydtrade
 * @Date: 2024-09-10 22:40
 * @Version: V1.0.0
 */

namespace app\admin\controller\merchant;

use app\common\enum\CommonEnum;
use app\common\enum\MerchantEnum;
use app\common\model;
use think\Controller;
use tpext\builder\traits\HasBuilder;

class Apply extends Controller
{
    use HasBuilder;

    protected $dataModel;

    protected $user_type;
    protected $status;

    protected function initialize()
    {
        parent::initialize();

        $this->dataModel = new model\Merchant();
        $this->pageTitle = '商户入驻';
        $this->enableField = 'status';
        $this->pagesize = 10;

        $this->indexWith = ['member'];

        $this->user_type = input('user_type', 0);
        $this->status = input('status', 0);
    }

    /**
     * 构建搜索
     *
     * @return void
     */
    protected function buildSearch()
    {
        $search = $this->search;
        $search->select('user_type', '商户归属')->options(MerchantEnum::storeTypeText(true))->default($this->user_type);
        $search->select('member_id', '管理员')->dataUrl(url('/admin/member/selectPage'));
        $search->select('merchant_type', '商户类型')->options(CommonEnum::merchantTypes(true));
        $search->select('status', '状态')->options([0 => '待审核', 2 => '已驳回', 4 => '申请中'])->default($this->status);
    }

    /**
     * 构建搜索条件
     * @return array
     */
    protected function filterWhere()
    {
        $searchData = request()->get();

        $where = [];
        if (isset($searchData['user_type']) && $searchData['user_type'] != '') {
            $where[] = ['user_type', 'eq', $searchData['user_type']];
        }
        if (isset($searchData['member_id']) && $searchData['member_id'] != '') {
            $where[] = ['member_id', 'eq', $searchData['member_id']];
        }
        if (isset($searchData['merchant_type']) && $searchData['merchant_type'] != '') {
            $where[] = ['merchant_type', 'eq', $searchData['merchant_type']];
        }
        if (isset($searchData['status']) && $searchData['status'] != '') {
            $where[] = ['status', 'eq', $searchData['status']];
        } else {
            $where[] = ['status', 'in', [0, 2, 4]];
        }
        return $where;
    }

    /**
     * 构建表格
     *
     * @return void
     */
    protected function buildTable(&$data = [])
    {
        $table = $this->table;

        $table->show('id', 'ID');
        $table->match('user_type', '商户归属')->options(MerchantEnum::storeTypeText(true))->mapClassGroup([[1, 'info'], [2, 'success']]);
        $table->match('merchant_type', '商户类型')->options(CommonEnum::merchantTypes(true));
        $table->show('merchant_short_name', '商户简称');
        $table->fields('contact_info', '商户联系信息')->with(
            $table->show('contact_name', '联系人'),
            $table->show('contact_phone', '联系电话'),
            $table->show('email', '联系邮箱')
        );
        $table->match('status', '状态')->options([0 => '待审核', 2 => '已驳回', 4 => '申请中'])->mapClassGroup([[0, 'success'], [2, 'danger'], [4, 'info']]);

        $table->fields('review_info', '审核信息')->with(
            $table->show('review_time', '审核时间'),
            $table->show('review_opinion', '审核意见')
        );

        $table->fields('times', '申请/修改时间')->with(
            $table->show('create_time', '申请时间'),
            $table->show('update_time', '修改时间')
        )->getWrapper()->addStyle('width:160px');

        $table->sortable('id, review_time, create_time');

        foreach ($data as &$d) {
            $d['__h_p__'] = $d['status'] != 0;
            $d['__h_unp__'] = $d['status'] != 0;
        }
        unset($d);

        $table->getToolbar()
            ->btnEnableAndDisable('通过', '拒绝')
            ->btnRefresh();

        $table->getActionbar()
            ->btnEdit()
            ->btnDelete()
            ->btnPostRowid('pass', url('enable', ['state' => 1]), '通过', 'btn-success', '', '')
            ->btnPostRowid('unpass', url('enable', ['state' => 0]), '拒绝', 'btn-danger', '', '')
            ->mapClass([
                'pass' => ['hidden' => '__h_p__'],
                'unpass' => ['hidden' => '__h_unp__'],
            ]);
    }

    /**
     * 审核
     * @param $state
     * @return \think\response\Json
     */
    public function enable($state)
    {
        $ids = input('post.ids', '');
        $ids = array_filter(explode(',', $ids), 'strlen');

        if (empty($ids)) {
            return json(['code' => 0, 'msg' => '参数有误']);
        }

        if ($state) {
            $remark = '审核通过';
            $status = 1;
        } else {
            $remark = '审核不通过';
            $status = 2;
        }
        $res = 0;
        foreach ($ids as $id) {
            if ($this->trans($id, $remark, $status)) {
                $res += 1;
            }
        }
        if ($res) {
            return json(['code' => 1, 'msg' => '成功操作' . $res . '条数据']);
        } else {
            trace('审核操作失败');
            return json(['code' => 0, 'msg' => '审核操作失败']);
        }
    }

    /**
     * 审核操作
     * @param $id
     * @param $remark
     * @param $state
     * @return model\OperationCenter|\think\response\Json
     */
    private function trans($id, $remark, $state = 1)
    {
        $records = $this->dataModel::where('id', $id)->find();

        if (!$records) {
            return json(['code' => 0, 'msg' => '记录不存在']);
        }
        if ($records['status'] != 0) {
            return json(['code' => 0, 'msg' => '记录状态不是待审核状态']);
        }

        $up_data = [
            'status' => $state,
            'review_opinion' => $remark,
            'update_time' => date_now(),
        ];
        if ($state == 1) {
            $up_data['review_time'] = date_now();
        }
        $res = $this->dataModel::where('id', $id)->update($up_data);

        return $res;
    }

    /**
     * 构建表单
     *
     * @param boolean $isEdit
     * @param array $data
     */
    protected function buildForm($isEdit, &$data = [])
    {
        $form = $this->form;

        $form->tab('基础信息');
        $form->defaultDisplayerSize(12, 12);

        $form->left()->with(
            $form->select('member_id', '管理员')->dataUrl(url('/admin/member/selectPage')),
            $form->select('parent_id', '上级推广人')->dataUrl(url('/admin/member/selectPage')),
            $form->text('username', '登录账号'),
            $form->text('password', '登录密码')->help('为空时不修改密码')->default(''),
        );

        $form->left()->with(
            $form->text('merchant_short_name', '商户简称'),
            $form->text('store_name', '门头名称'),
            $form->text('contact_name', '联系人姓名'),
            $form->text('contact_phone', '联系电话'),
            $form->text('email', '联系邮箱'),
        );

        $form->tab('经营信息');
        $form->fields('', '', 10)->size(0, 12)->showLabel(false);
        $form->text('legal_name', '经营者姓名');
        $form->text('legal_num', '经营者身份证号');
        $form->textarea('legal_address', '经营者身份证上的居住地');
        $form->image('legal_idcard_front_photo', '经营者身份证正面');
        $form->image('legal_idcard_back_photo', '经营者身份证反面');
        $form->image('legal_hand_hold_idcard_photo', '经营者手持身份证照');
        $form->date('legal_idcard_begin_date', '经营者身份证有效期始');
        $form->radio('legal_idcard_validity_type', '长期有效')->options([0 => '短期', 1 => '长期'])->default(0)->when(0)->with(
            $form->date('legal_idcard_end_date', '经营者身份证有效期止'),
        );

        $form->text('license_name', '营业执照公司名');
        $form->text('license_code', '营业执照信用代码');
        $form->textarea('license_address', '营业执照注册地址');
        $form->image('license_photo', '营业执照照片');
        $form->date('license_begin_date', '营业执照有效期始');
        $form->radio('license_validity_type', '长期有效')->options([0 => '短期', 1 => '长期'])->default(0)->when(0)->with(
            $form->date('license_end_date', '营业执照有效期止'),
        );

        $form->fieldsEnd();

        $form->tab('结算信息');
        $form->fields('', '', 10)->size(0, 12)->showLabel(false);
        $form->radio('account_type', '结算账户类型')->options([1 => '个人账户', 2 => '企业账户'])->default(2);
        $form->radio('settle_type', '结算人类型')->options([1 => '非法人结算', 2 => '法人结算', 3 => '对公结算'])->default(3);
        $form->fieldsEnd();
    }

    /**
     * 保存数据
     *
     * @param integer $id
     * @return void
     */
    private function save($id = 0)
    {
        $data = request()->only([], 'post');

        $result = $this->validate($data, []);

        if (!$result) {
            $this->error($result);
        }

        if ($id) {
            // 编辑
            $data['update_time'] = date_now();
        } else {
            // 新增
            $data['create_time'] = date_now();
            $data['update_time'] = date_now();
        }

        return $this->doSave($data, $id);
    }

}